﻿using MediatR;
using MS.Data.API.Read.Command.RoleInfo;
using MS.Data.Domain;
using MS.Data.ErrorCode;
using MS.Data.Infratructrue.Istanbul;

namespace MS.Data.API.Read.CommandHandle.RoleInfo
{
    public class GetRoleCommandHandel : IRequestHandler<GetRoleCommand, APIResult<APIPing<Role>>>
    {
        IBaseRepository<Role> roleRep;

        public GetRoleCommandHandel(IBaseRepository<Role> roleRep)
        {
            this.roleRep = roleRep;
        }

        public Task<APIResult<APIPing<Role>>> Handle(GetRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPing<Role>> result = new APIResult<APIPing<Role>>();
            result.code = APIEnum.显示成功;
            result.mes = APIEnum.显示成功.ToString();

            var list = from a in roleRep.GetAll()
                       where !a.IsDel
                       select new Role()
                       {
                           RoleId=a.RoleId,
                           RoleName=a.RoleName,
                           CreaTime=a.CreaTime,
                           PessionName=a.PessionName,
                           State=a.State,
                       };
            if (!string.IsNullOrEmpty(request.RoleName))
            {
                list = list.Where(s => s.RoleName.Contains( request.RoleName));
            }

            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);

            list = list.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);

            APIPing<Role> page = new APIPing<Role>()
            {
                totalCount = totalCount,
                pageCount = pageCount,
                pageData = list.ToList(),
            };
            result.data = page;
            return Task.FromResult(result);
        }
    }
}
